package com.fowo.api.tiktok.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.datainterface.constants.Constants;
import com.fowo.api.datainterface.entity.DatainterfaceAuthority;
import com.fowo.api.datainterface.service.DatainterfaceAuthorityService;
import com.fowo.api.datainterface.service.impl.DatainterfaceServiceImpl;
import com.fowo.api.datainterface.util.Common;
import com.fowo.api.entity.ShopInfo;
import com.fowo.api.entity.TmpTiktokProduct;
import com.fowo.api.model.shop.info.ShopInfoVo;
import com.fowo.api.service.impl.ShopInfoServiceImpl;
import com.fowo.api.service.impl.TmpTiktokProductServiceImpl;
import com.fowo.api.tiktok.mapper.SyncTiktokMapper;
import com.fowo.api.tiktok.util.TiktokUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

@Component
@Slf4j
public class TiktokProductSyncService {
    @Resource
    private DatainterfaceAuthorityService datainterfaceAuthorityBaseService;
    @Resource
    private Common common;
    @Resource
    private ShopInfoServiceImpl shopInfoService;
    @Resource
    private TmpTiktokProductServiceImpl tmpTiktokProductService;
    @Resource
    private SyncTiktokMapper syncTiktokMapper;
    @Resource
    private DatainterfaceServiceImpl datainterfaceService;

    public static final String PRODUCT_URL = "/product/202312/products/search";

    public static final String CREATE_PRODUCT_URL = "/product/202309/global_products";

    public void syncProduct(){
        //清空临时表
        syncTiktokMapper.deleteTmpTiktokProduct();
        //拉去数据到临时表
        getProductList();

        //同步到正式表
        syncTiktokMapper.updateTiktokProduct();
        syncTiktokMapper.insertTiktokProduct();
        //同步到配对列表
//        syncTiktokMapper.insertPariList();
    }

    public void getProductList(){

        final List<ShopInfo> list = shopInfoService.list(Wrappers.lambdaQuery(ShopInfo.class)
                .eq(ShopInfo::getPlatform,"TikTok")
                .eq(ShopInfo::getSellerAuthStatus,"SQ01"));

        for(ShopInfo shopInfo : list){
            Map<String,String> header = new HashMap<>();
            header.put("x-tts-access-token", shopInfo.getRefreshToken());

            int page_size = 100;

            Map<String,Object> query = new TreeMap<>();
            query.put("access_token",shopInfo.getRefreshToken());
            query.put("shop_cipher",shopInfo.getMarketplaceId());
            query.put("page_size",page_size);

            Map<String,Object> params = new HashMap<>();
            params.put("update_time_ge", DateUtil.yesterday().getTime()/1000L);

            Map<String,Object> currentParamsMap = new HashMap<>();
            currentParamsMap.put("params",params);
            currentParamsMap.put("query",query);

            Object result = datainterfaceService.executeInterface(null, "EC00531", null, currentParamsMap, header);

            JSONObject body = JSONUtil.parseObj(result);
            if(body.getInt("code") == 0){
                JSONObject data = body.getJSONObject("data");
                JSONArray products = data.getJSONArray("products");
                //保存到临时表
                saveToTmp(products,shopInfo);
                int totalCount = data.getInt("total_count");
                String nextPageToken = data.getStr("next_page_token");
                int page = totalCount/page_size;
                if(totalCount%page_size != 0){
                    page += 1;
                }
                for(int i = 1 ; i < page ; i++){
                    if(StrUtil.isNotBlank(nextPageToken)){ //下一页
                        nextPageToken = getNext(nextPageToken,shopInfo);
                    }
                }
            }else {
                log.error("拉去Tiktok产品异常，"+body.getStr("message"));
            }
        }
    }

    public String getNext(String nextPageToken,ShopInfo shopInfo){

        Map<String,String> header = new HashMap<>();
        header.put("x-tts-access-token", shopInfo.getRefreshToken());

        int page_size = 100;

        Map<String,Object> query = new TreeMap<>();
        query.put("access_token",shopInfo.getRefreshToken());
        query.put("shop_cipher",shopInfo.getMarketplaceId());
        query.put("page_size",page_size);
        query.put("page_token",nextPageToken);

        Map<String,Object> params = new HashMap<>();
        params.put("update_time_ge", DateUtil.yesterday().getTime()/1000L);

        Map<String,Object> currentParamsMap = new HashMap<>();
        currentParamsMap.put("params",params);
        currentParamsMap.put("query",query);

        Object result = datainterfaceService.executeInterface(null, "EC00531", null, currentParamsMap, header);

        JSONObject body = JSONUtil.parseObj(result);
        if(body.getInt("code") == 0){
            JSONObject data = body.getJSONObject("data");
            JSONArray products = data.getJSONArray("products");
            //保存到临时表
            saveToTmp(products,shopInfo);

            return data.getStr("next_page_token");
        }else {
            log.error("拉去Tiktok产品异常，"+body.getStr("message"));
        }
        return null;
    }

//    public void getProductList(){
//        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"TikTok"), false);
//        String rootPath = entityAuthority.getRootPath();
//        String appKey = common.getAuthoritySimpleFactory(entityAuthority, "appKey");
//        String appSecret = common.getAuthoritySimpleFactory(entityAuthority, "appSecret");
//
//        final List<ShopInfo> list = shopInfoService.list(Wrappers.lambdaQuery(ShopInfo.class)
//                .eq(ShopInfo::getPlatform,"TikTok")
//                .eq(ShopInfo::getSellerAuthStatus,"SQ01"));
//
//        for(ShopInfo shopInfo : list){
//            HttpHeaders header = new HttpHeaders();
//            header.set("Content-Type", "application/json");
//            header.set("x-tts-access-token", shopInfo.getRefreshToken());
//
//            Long timestamp = System.currentTimeMillis()/1000;
//            int page_size = 100;
//
//            Map<String,Object> query = new TreeMap<>();
//            query.put("access_token",shopInfo.getRefreshToken());
//            query.put("app_key",appKey);
//            query.put("shop_cipher",shopInfo.getMarketplaceId());
//            query.put("timestamp",timestamp);
//            query.put("page_size",page_size);
//
//            Map<String,Object> params = new HashMap<>();
//            params.put("update_time_ge", DateUtil.yesterday().getTime()/1000L);
//
//            String sign = TiktokUtil.getSign(appSecret,PRODUCT_URL,query,null);
//            query.put("sign",sign);
//
//            StringBuilder pathParam = new StringBuilder();
//            for(String key : query.keySet()){
//                pathParam.append("&").append(key).append("=").append(query.get(key));
//            }
//            String url = rootPath + PRODUCT_URL + "?" + pathParam.substring(1);
//            Object result = TiktokUtil.getBaseAspect().httpRequest(url, HttpMethod.POST, null, header, Object.class, Constants.Read, StrUtil.EMPTY);
//
//            JSONObject body = JSONUtil.parseObj(result);
//            if(body.getInt("code") == 0){
//                JSONObject data = body.getJSONObject("data");
//                JSONArray products = data.getJSONArray("products");
//                //保存到临时表
//                saveToTmp(products,shopInfo);
//                int totalCount = data.getInt("total_count");
//                String nextPageToken = data.getStr("next_page_token");
//                int page = totalCount/page_size;
//                if(totalCount%page_size != 0){
//                    page += 1;
//                }
//                for(int i = 1 ; i < page ; i++){
//                    if(StrUtil.isNotBlank(nextPageToken)){ //下一页
//                        nextPageToken = getNext(entityAuthority,nextPageToken,shopInfo);
//                    }
//                }
//            }else {
//                log.error("拉去Tiktok产品异常，"+body.getStr("message"));
//            }
//        }
//    }
//
//    public String getNext(DatainterfaceAuthority entityAuthority,String nextPageToken,ShopInfo shopInfo){
//        String rootPath = entityAuthority.getRootPath();
//        String appKey = common.getAuthoritySimpleFactory(entityAuthority, "appKey");
//        String appSecret = common.getAuthoritySimpleFactory(entityAuthority, "appSecret");
//
//        HttpHeaders header = new HttpHeaders();
//        header.set("Content-Type", "application/json");
//        header.set("x-tts-access-token", shopInfo.getRefreshToken());
//
//        Long timestamp = System.currentTimeMillis()/1000;
//        int page_size = 100;
//
//        Map<String,Object> query = new TreeMap<>();
//        query.put("access_token",shopInfo.getRefreshToken());
//        query.put("app_key",appKey);
//        query.put("shop_cipher",shopInfo.getMarketplaceId());
//        query.put("timestamp",timestamp);
//        query.put("page_size",page_size);
//        query.put("page_token",nextPageToken);
//
//        Map<String,Object> params = new HashMap<>();
//        params.put("update_time_ge", DateUtil.yesterday().getTime()/1000L);
//
//        String sign = TiktokUtil.getSign(appSecret,PRODUCT_URL,query,null);
//        query.put("sign",sign);
//
//        StringBuilder pathParam = new StringBuilder();
//        for(String key : query.keySet()){
//            pathParam.append("&").append(key).append("=").append(query.get(key));
//        }
//        String url = rootPath + PRODUCT_URL + "?" + pathParam.substring(1);
//
//        Object result = TiktokUtil.getBaseAspect().httpRequest(url, HttpMethod.POST, null, header, Object.class, Constants.Read, StrUtil.EMPTY);
//
//        JSONObject body = JSONUtil.parseObj(result);
//        if(body.getInt("code") == 0){
//            JSONObject data = body.getJSONObject("data");
//            JSONArray products = data.getJSONArray("products");
//            //保存到临时表
//            saveToTmp(products,shopInfo);
//
//            return data.getStr("next_page_token");
//        }else {
//            log.error("拉去Tiktok产品异常，"+body.getStr("message"));
//        }
//        return null;
//    }

    public void saveToTmp(JSONArray products,ShopInfo shopInfo){
        List<TmpTiktokProduct> list = new ArrayList<>();
        for(int i = 0 ; i < products.size() ; i++){
            JSONObject jsonObject = products.getJSONObject(i);
            String productId = jsonObject.getStr("id");
            String title = jsonObject.getStr("title");
            String status = jsonObject.getStr("status");//DRAFT, PENDING, FAILED, ACTIVATE, SELLER_DEACTIVATED, PLATFORM_DEACTIVATED, FREEZE, DELETED.
            String salesRegions = jsonObject.getStr("sales_regions");
            Date createTime = jsonObject.getDate("create_time");
            Date updateTime = jsonObject.getDate("update_time");
            JSONArray skus = jsonObject.getJSONArray("skus");
            for(int j = 0 ; j < skus.size() ; j++){
                TmpTiktokProduct tmpTiktokProduct = new TmpTiktokProduct();
                tmpTiktokProduct.setSid(shopInfo.getId());
                tmpTiktokProduct.setCreateTime(new Date());
                tmpTiktokProduct.setLastUpdateTime(new Date());
                tmpTiktokProduct.setProductId(productId);
                tmpTiktokProduct.setTitle(title);
                tmpTiktokProduct.setStatus(status);
                tmpTiktokProduct.setSalesRegions(salesRegions);
                tmpTiktokProduct.setPlatformCreateTime(createTime);
                tmpTiktokProduct.setPlatformUpdateTime(updateTime);
                JSONObject skuObject = skus.getJSONObject(j);
                tmpTiktokProduct.setSkuId(skuObject.getStr("id"));
                tmpTiktokProduct.setSellerSku(skuObject.getStr("seller_sku"));
                JSONObject price = skuObject.getJSONObject("price");
                tmpTiktokProduct.setCurrency(price.getStr("currency"));
                tmpTiktokProduct.setSalePrice(price.getBigDecimal("sale_price"));
                tmpTiktokProduct.setTaxExclusivePrice(price.getBigDecimal("tax_exclusive_price"));
                list.add(tmpTiktokProduct);
            }
        }
        tmpTiktokProductService.saveBatch(list);
    }

}
